package com.ruoyi.system.outto.goods.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.util.UrlUtils;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ImgUntil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.gameAttr.service.IGameAttributeService;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.V2.inter.mapper.SelectPushMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.goods.MONITAOHAOHAOAPI;
import com.ruoyi.system.sms.service.ISendSms;
import com.ruoyi.system.utils.AliUtils;
import com.ruoyi.system.utils.MultipartFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MONITAOHAOHAOApiImpl implements MONITAOHAOHAOAPI {

    static String phone = "18537003990";
    static String account = "j2kcVUtJMTkMkqQ96NPievsGFDqnYehXysdRg6Iv";
    @Resource
    private IGameAttributeService gameAttributeService;
    @Resource
    InterAttrMapper interAttrMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISendSms sendSms;
    @Autowired
    private SelectPushMapper selectPushMapper;


    public static void main(String[] args) {
//        long givenTimestamp = 1733554074L;
//        boolean b = compareTime(1733554074L);
//        System.out.println(b);
        String body = HttpRequest.get("https://api.taohaohaoapp.com/app/sts").execute().body();
        System.out.println(body);
    }

    static boolean compareTime(Long oldTime) {
        long givenTimestampInMillis = oldTime * 1000L;
        long currentTimestampInMillis = System.currentTimeMillis();
        if (currentTimestampInMillis > givenTimestampInMillis) {
            return false;
        } else {
            return true;
        }
    }

    private void builderServer(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String server) {

        JSONObject serjsonObject = JSONObject.parseObject(server);
        //开始匹配一级区服
        String interServeReqs = serjsonObject.getString("interServeReqs");
        String qufuid = "";
        if (Objects.equals(goodsInfoAndAttrValueDto.getGameType(), "0")) {
            qufuid = goodsInfoAndAttrValueDto.getSystemId() + "" + goodsInfoAndAttrValueDto.getCarrierId() + "";
        } else {
            qufuid = goodsInfoAndAttrValueDto.getServerId() + "";
        }
        List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);

        for (JSONObject object : oneServer) {
            String ydServeId = object.getString("YdServeId");
            if (StringUtils.isNotEmpty(ydServeId)) {
                ydServeId = ydServeId.replace(",", "").replace(" ", "");
                if (Objects.equals(ydServeId, qufuid)) {
                    String twoServeStr = object.getString("interServerRes");
                    List<JSONObject> twoServer = JSONObject.parseArray(twoServeStr, JSONObject.class);
                    params.put("partition_id", object.getString("id"));
                }
            }
        }
    }

    private void builderRadioAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, List<Object> propertys, String radioAttr) {

        //========================开始匹配单选属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(radioAttr);
        String interRadioReqs = jsonObject.getString("interRadioReqs");
        log.info(JSONObject.toJSONString(interRadioReqs));
        List<JSONObject> jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
        if (CollectionUtils.isEmpty(jsonObjects)) {
            throw new GlobalException("接口单选属性暂未配置");
        }
        /**
         * 1、先查询自定义中所有单选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        gameAttrTemplate.setFieldType("radio");
        List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();


        List<JSONObject> defObjects = new ArrayList<>();
        defObjects.addAll(jsonObjects);
        for (JSONObject object : jsonObjects) {
            JSONObject params = new JSONObject();
            params.put("component", object.getString("id").split(",")[1]);
            params.put("goods_property_id", 0);
            params.put("property_id", Integer.parseInt(object.getString("id").split(",")[0]));
            for (GameAttrTemplate attrTemplate : gameAttrTemplates) {
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        //一级属性
                        //注意 YdConfigId 对应的是 f字段对应的 id
                        if (Objects.equals(object.getLong("YdConfigId"), attrTemplate.getId())) {

                            defObjects.remove(object);//如果匹配上，则去掉
                            String interRadioReqs1 = object.getString("interRadioReqs");
                            List<JSONObject> jsonObjects2 = JSONObject.parseArray(interRadioReqs1, JSONObject.class);
                            declaredField.setAccessible(true);
                            try {
                                //获取选择的值 例如  实名中的可二次
                                Object o = declaredField.get(goodsInfoAndAttrValueDto);
                                String oneValue = String.valueOf(o);
                                List<JSONObject> twoAttr = jsonObjects2.stream().filter(j -> StringUtils.isNotEmpty(j.getString("YdConfigId")) ? j.getString("YdConfigId").contains(oneValue) : "1".contains(oneValue)).collect(Collectors.toList());
                                String interConfigName = object.getString("InterConfigName");
                                String defaultValue = object.getString("defaultValue");
                                if (CollectionUtils.isEmpty(twoAttr)) {
                                    if (StringUtils.isNotEmpty(defaultValue)) {
                                        params.put("property_value", defaultValue);
                                    }
                                }
                                if (!CollectionUtils.isEmpty(twoAttr)) {
                                    JSONObject jsonObject2 = twoAttr.get(0);
                                    String interConfigId2 = jsonObject2.getString("InterConfigId");
                                    params.put("property_value", interConfigId2);
                                }
                            } catch (Exception e) {
                                throw new GlobalException("单选项" + attrTemplate.getFieldName() + "匹配错误");
                            }
                        }
                    }
                }
            }
            if (StringUtils.isNotEmpty(params.getString("property_value"))) {
                propertys.add(params);
            }
        }
        //开始匹配默认值
        for (JSONObject object : defObjects) {
            JSONObject params = new JSONObject();
            params.put("component", object.getString("id").split(",")[1]);
            params.put("goods_property_id", 0);
            params.put("property_id", Integer.parseInt(object.getString("id").split(",")[0]));
            String interRadioReqss = object.getString("interRadioReqs");
            List<JSONObject> jsonObjectss = JSONObject.parseArray(interRadioReqss, JSONObject.class);
            for (JSONObject jsonObject1 : jsonObjectss) {
                if (StringUtils.isNotEmpty(jsonObject1.getString("defaultValue"))) {
                    params.put("property_value", jsonObject1.getString("defaultValue"));
                    break;
                }
            }
            if (StringUtils.isNotEmpty(params.getString("property_value"))) {
                propertys.add(params);
            }
        }
        //========================单选属性匹配结束=====================//
    }

    private void builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, List<Object> propertys, String checkAttr) {
        //========================开始匹配多选属性=====================//
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
        String interCheckBoxReqs = checkAttrJson.getString("interCheckBoxReqs");
        List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
        if (CollectionUtils.isEmpty(checkAttrJson)) {
            throw new GlobalException("接口多选属性暂未配置");
        }

        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        List<String> types = new ArrayList<>();
        types.add("checkbox");
        types.add("boxradio");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);

        for (JSONObject object : checkJsonList) {
            JSONObject params = new JSONObject();
            params.put("component", object.getString("id").split(",")[1]);
            params.put("goods_property_id", 0);
            params.put("property_id", Integer.parseInt(object.getString("id").split(",")[0]));
            String string = "";
            for (GameAttrTemplate attrTemplate : checkAttrTemplates) {
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        declaredField.setAccessible(true);

                        String ydConfigIdLeveOne = object.getString("YdConfigId");
                        if (StringUtils.isNotEmpty(ydConfigIdLeveOne)) {

                            String[] split2 = ydConfigIdLeveOne.split(",");
                            List<String> list2 = new ArrayList<>();
                            for (String s : split2) {
                                s = s.replace(" ", "");
                                list2.add(s);
                            }
                            if (list2.contains(attrTemplate.getId() + "")) {
                                Object o = null;
                                try {
                                    o = declaredField.get(goodsInfoAndAttrValueDto);
                                } catch (IllegalAccessException e) {
                                    throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                                }
                                String oneValue = String.valueOf(o);
                                if(StringUtils.isNotEmpty(oneValue)) {
                                    //一级属性
                                    String ydConfigId = object.getString("YdConfigId");
                                    String InterConfigName = object.getString("InterConfigName");
                                    if (StringUtils.isNotEmpty(ydConfigId)) {
                                        ydConfigId = ydConfigId.replace(" ", "");
                                        String[] split = ydConfigId.split(",");
                                        //一级属性已经匹配，开始匹配二级属性
                                        if (Arrays.asList(split).contains(attrTemplate.getId() + "")) {
                                            String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
//                                        String interCheckBoxReqsStr = object.getString("interServerRes");
                                            //开始匹配二级属性
                                            List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                                            /**
                                             * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                                             */
                                            for (JSONObject jsonObject1 : jsonObjects2) {
                                                if (StringUtils.isNotEmpty(oneValue)) {
                                                    String[] split1 = oneValue.split(",");
                                                    String ydConfigId1 = jsonObject1.getString("YdConfigId");
                                                    if (StringUtils.isNotEmpty(ydConfigId1)) {
                                                        ydConfigId1 = ydConfigId1.replace(" ", "");
                                                        for (String s : split1) {
                                                            if (goodsInfoAndAttrValueDto.getGameName().equals("原神")) {
                                                                GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(s));
                                                                GameAttribute gameAttribute2 = gameAttributeMapper.selectGameAttributeById(gameAttribute1.getParentId());
                                                                s = gameAttribute2.getId().toString();
                                                            }
                                                            if (goodsInfoAndAttrValueDto.getGameName().equals("崩坏星穹铁道")) {
                                                                GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(s));
                                                                GameAttribute gameAttribute2 = gameAttributeMapper.selectGameAttributeById(gameAttribute1.getParentId());
                                                                s = gameAttribute2.getId().toString();
                                                            }
                                                            if (Objects.equals(s, ydConfigId1)) {
                                                                String InterConfigId2 = jsonObject1.getString("InterConfigId");
                                                                string += "," + InterConfigId2;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    } else {
                                        throw new GlobalException("属性参数错误，请匹配后重新配置");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (StringUtils.isNotEmpty(string)) {
                params.put("property_value", string.substring(1));
                propertys.add(params);
            }
        }
        //========================多选属性匹配完成=====================//
    }

    private void builderInputAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, List<Object> propertys, String inputAttr) {
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();

        //========================开始匹配输入框=====================//
        JSONObject jsonObject1 = JSONObject.parseObject(inputAttr);
        String inputJson = jsonObject1.getString("inputJson");
        List<JSONObject> jsonObjects1 = JSONObject.parseArray(inputJson, JSONObject.class);
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        ArrayList types = new ArrayList<>();
        types.add("number");
        types.add("input");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> inputTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        List<JSONObject> defInputObjects = new ArrayList<>();
        defInputObjects.addAll(jsonObjects1);
        for (JSONObject object : jsonObjects1) {
            JSONObject params = new JSONObject();
            params.put("component", object.getString("id").split(",")[1]);
            params.put("goods_property_id", 0);
            params.put("property_id", Integer.parseInt(object.getString("id").split(",")[0]));
            for (GameAttrTemplate inputTemplate : inputTemplates) {
                String aavName = inputTemplate.getAavName();
                if (Objects.equals(object.getString("aavName"), inputTemplate.getAavName())) {
                    defInputObjects.remove(object);
                    String aavNameInter = object.getString("interName");
                    String interId = object.getString("interId");
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (Objects.equals(aavName, name)) {
                            declaredField.setAccessible(true);
                            String oneValue = null;
                            try {
                                oneValue = (String) declaredField.get(goodsInfoAndAttrValueDto);
                            } catch (IllegalAccessException e) {
                                throw new GlobalException("3属性参数错误，请匹配后重新配置");
                            }
                            if (StringUtils.isNotEmpty(oneValue)) {
                                params.put("property_value", oneValue);
                            }
                        }
                    }
                }
            }
            if (StringUtils.isNotEmpty(params.getString("property_value"))) {
                propertys.add(params);
            }
        }
        //开始匹配默认值
        for (JSONObject object : defInputObjects) {
            JSONObject params = new JSONObject();
            params.put("component", object.getString("id").split(",")[1]);
            params.put("goods_property_id", 0);
            params.put("property_id", Integer.parseInt(object.getString("id").split(",")[0]));
            String defaultValue = object.getString("defaultValue");
            if (StringUtils.isNotEmpty(defaultValue)) {
                params.put("property_value", "0");
                propertys.add(params);
            }
        }
    }

    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, InterAttr interAttr, SalePartner salePartner) {
        Map<String, Object> params = new HashMap<>();

        params.put("game_id", Integer.parseInt(interAttr.getInterGameId().split(",")[0]));
        params.put("business_id", Integer.parseInt(interAttr.getInterGameId().split(",")[1]));
        params.put("business_type", Integer.parseInt(interAttr.getInterGameId().split(",")[2]));

        params.put("has_qrcode", false);

        params.put("stock", 1);
        String title = goodsInfoAndAttrValueDto.getDes().length() > 400 ? goodsInfoAndAttrValueDto.getDes().substring(0, 400) : goodsInfoAndAttrValueDto.getDes();
        params.put("goods_title", title);
        List<Object> medias = new ArrayList<>();

        JSONObject jsonObject = new JSONObject();
        String string = upLoadImg(goodsInfoAndAttrValueDto.getTitleImg(), null);
        jsonObject.put("url", string);
        jsonObject.put("type", 1);
        jsonObject.put("width", 714);
        jsonObject.put("height", 1920);
        jsonObject.put("sort", 1);
        jsonObject.put("media_id", 0);
        medias.add(jsonObject);

        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        Collections.shuffle(infoImgs);
        infoImgs = infoImgs.subList(1, infoImgs.size());
        int i = 2;
        for (GoodsInfoImg goodsInfoImg1 : infoImgs) {
            i++;
            jsonObject = new JSONObject();
            string = upLoadImg(goodsInfoImg1.getImgUrl(), null);
            jsonObject.put("url", string);
            jsonObject.put("type", 1);
            jsonObject.put("width", 714);
            jsonObject.put("height", 1920);
            jsonObject.put("sort", i);
            jsonObject.put("media_id", 0);
            medias.add(jsonObject);
        }
        params.put("medias", medias);
        params.put("price", goodsInfoAndAttrValueDto.getPrice());
        params.put("account", goodsInfoAndAttrValueDto.getAccountNumber());
        params.put("password", "123456");

        builderServer(goodsInfoAndAttrValueDto, params, interAttr.getServer());

        List<Object> propertys = new ArrayList<>();
        //开始匹配单选属性
        builderRadioAttr(goodsInfoAndAttrValueDto, propertys, interAttr.getRadioAttr());
        //开始匹配多选属性
        builderCheckAttr(goodsInfoAndAttrValueDto, propertys, interAttr.getCheckAttr());
        //开始匹配输入框属性
        builderInputAttr(goodsInfoAndAttrValueDto, propertys, interAttr.getInputAttr());

        if(goodsInfoAndAttrValueDto.getGameName().equals("枪战王者")){
            if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF2())) {
                GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF2()));
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("component", "input");
                jsonObject1.put("goods_property_id", 0);
                jsonObject1.put("property_id", 45);
                jsonObject1.put("property_value", gameAttribute1.getFieldName().replace("V",""));
                propertys.add(jsonObject1);
            }
        }
        params.put("propertys", propertys);
        List leases = new ArrayList();
        params.put("leases", leases);
        return params;
    }

    private List<GameAttribute> getGameAttributs(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        return gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                Long.class));
    }

    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }

    public static String getGoods(String account, String gameId, String cookie) {
        String url = "https://kejinlianmeng.com/account/goods/index?game_id=" + gameId + "&status=0&id=&keyword=&tpg_id=&game_account=" + account;
        String result = HttpRequest.get(url).header("Accept", "*/*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .header("Cookie", cookie)
                .header("Origin", "https://kejinlianmeng.com")
                .header("Pragma", "no-cache")
                .header("Referer", "https://kejinlianmeng.com/account/goods/establish?game_id=1&back_url=https%3A%2F%2Fkejinlianmeng.com%2Faccount%2Fgoods%2Findex%3F_pjax%3D%2523main%26game_id%3D1")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-origin")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36")
                .header("X-Requested-With", "XMLHttpRequest")
                .header("sec-ch-ua", "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .execute()
                .body();
        Document doc = Jsoup.parse(result);
        Element p = doc.select("tbody").first();
        String text = p.text().split(" ")[0].trim();
        return text;
    }

    public static String upper(String goodId, String cookie) {
        String url = "https://kejinlianmeng.com/account/goods/upper/" + goodId;
        String result = HttpRequest.post(url)
                .header("Accept", "*/*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .header("Cookie", cookie)
                .header("Origin", "https://kejinlianmeng.com")
                .header("Pragma", "no-cache")
                .header("Referer", "https://kejinlianmeng.com/account/goods/establish?game_id=1&back_url=https%3A%2F%2Fkejinlianmeng.com%2Faccount%2Fgoods%2Findex%3F_pjax%3D%2523main%26game_id%3D1")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-origin")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36")
                .header("X-Requested-With", "XMLHttpRequest")
                .header("sec-ch-ua", "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .execute()
                .body();
        return result;
    }

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        //属性匹配
//        String substring = salePartner.getSaleName().substring(salePartner.getSaleName().indexOf("_")+1);
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(salePartner.getSaleName(), goodsInfoAndAttrValueDto.getGameId());
        if (StringUtils.isEmpty(interAttr.getInterGameId())) {
            throw new GlobalException("该游戏属性暂未匹配!!!" + goodsInfoAndAttrValueDto.getGameName());
        }
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, interAttr, salePartner);
        log.info("淘号号添加接口请求参数={}", JSONObject.toJSONString(params));
        String url = "https://api.taohaohaoapp.com/app/goods/publish";
        String result = HttpRequest.post(url)
                .body(JSONObject.toJSONString(params))
                .header("Authorization", salePartner.getSaleKey())
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/json")
                .execute()
                .body();
        System.out.println(result);
        log.info("淘号号添加接口返回参数={}", result);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"0".equals(resultJson.getString("err_code"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
            String data = resultJson.getString("data");
            String goods_id = JSONObject.parseObject(data).getString("goods_id");
            resultMap.put("outId", goods_id);
        }
        resultMap.put("req", JSONObject.toJSONString(params));
        resultMap.put("res", result);
        resultMap.put("msg", resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        //属性匹配
        String substring = salePartner.getSaleName().substring(salePartner.getSaleName().indexOf("_") + 1);
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());
        if (StringUtils.isEmpty(interAttr.getInterGameId())) {
            throw new GlobalException("该游戏属性暂未匹配!!!" + goodsInfoAndAttrValueDto.getGameName());
        }
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, interAttr, salePartner);
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        ArtRec artRec = artRecs.get(0);
        params.put("goods_id", Integer.parseInt(artRec.getOutid()));
        log.info("淘号号编辑接口请求参数={}", JSONObject.toJSONString(params));
        String url = "https://api.taohaohaoapp.com/app/goods/publish";
        String result = HttpRequest.post(url)
                .body(JSONObject.toJSONString(params))
                .header("Authorization", salePartner.getSaleKey())
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/json")
                .execute()
                .body();
        System.out.println(result);
        log.info("淘号号编辑接口返回参数={}", result);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"0".equals(resultJson.getString("err_code"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
        }
        resultMap.put("req", JSONObject.toJSONString(params));
        resultMap.put("res", result);
        resultMap.put("msg", resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> params = new TreeMap<>();
        params.put("action", 2);
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        if(CollectionUtils.isEmpty(artRecs)){
            throw new GlobalException("当前账号三方ID未保存!!!");
        }
        ArtRec artRec = artRecs.get(0);
        params.put("goods_id", Integer.parseInt(artRec.getOutid()));
        log.info("淘号号删除接口请求参数={}", JSONObject.toJSONString(params));
        String url = "https://api.taohaohaoapp.com/app/user/goods/shelf";
        String result = HttpRequest.post(url)
                .body(JSONObject.toJSONString(params))
                .header("Authorization", salePartner.getSaleKey())
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/json")
                .execute()
                .body();
        System.out.println(result);
        log.info("淘号号删除接口返回参数={}", result);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"0".equals(resultJson.getString("err_code"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
        }
        resultMap.put("req", JSONObject.toJSONString(params));
        resultMap.put("res", result);
        resultMap.put("msg", resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }


    private static void login(String smsCode, String phone) {
        String send = "https://kejinlianmeng.com/api_v1/system/auth/login";

        /**
         * {
         *     "passport": "18537003990",
         *     "captcha": "111111",
         *     "password": "",
         *     "device_id": "",
         *     "device_type": "web",
         *     "guard": "web",
         *     "timestamp": 1726294975,
         *     "nonce": "d5d782cd099355d6f0c5fe8a7f18ea31",
         *     "sign": "88ed6c0"
         * }
         */

        TreeMap params = new TreeMap();
        params.put("passport", phone);
        params.put("captcha", smsCode);
        params.put("password", "");
        params.put("device_id", "");
        params.put("device_type", "web");
        params.put("guard", "web");
        String s = new Date().getTime() / 1000 + "";
        params.put("timestamp", s);
        String nonce = nonce();
        params.put("nonce", nonce);

        String sign = sign(params);
        params.put("sign", sign);

        String cookie = getCookie(null);

        JSONObject jsonObject = new JSONObject(params);
        String s3 = jsonObject.toString();
        System.out.println(s3);
        String body = HttpRequest.post(send)
                .header("x-app-source", "pc")
                .header("x-os", "pc")
                .header("x-type", "user")
                .header("x-ver", "2.39.0")
                .header("cookie", cookie)
                .body(s3)
                .execute()
                .body();
        log.info("验证码发送结果={}", body);
        log.info("cookie:" + cookie);
    }

    private static String getToken(SalePartner salePartner) {
        String cookie = "account=" + account + "; _ga=GA1.1.2133416559.1726621808; acw_tc=ac11000117266272807932614e00e00608a859cf72b9d0f1ed3cb79246450c; _ga_TJJQCLLECR=GS1.1.1726627284.2.0.1726627284.0.0.0";

        String push = "https://kejinlianmeng.com/account/goods/establish?game_id=1&back_url=https%3A%2F%2Fkejinlianmeng.com%2Faccount%2Fgoods%2Findex%3F_pjax%3D%2523main%26game_id%3D1&_pjax=%23main";
//        String push = "https://kejinlianmeng.com/account/dashboard/good_num";
//            Document document = Jsoup.connect(push)
//                    .header("cookie","remember_web=eyJpdiI6ImxYM3dlVGxxbTVuWEJTNklXalZoM1E9PSIsInZhbHVlIjoiemhiY0h1MkF2U0hZUlo3eDVJbURkMHA1ZWNiR0l1MVRsNW1kQkFwUlZzcGw5S0NEWFRjUlhSU0R6blo5VkFqQWFEZllPUDNrd1dlUFNJVzZIakdqM1JiaEFmU0FSckEzOFwvRXQybTc1clBKWllVOVhzVnJnaWRsdHptcktvXC9ZSTdLOG01YjJ3M2ZXd2RqTmhpNkdFazE4TXhWdjJibCtOajdlZTFIb2xKWjJlNjV0UVhhNFpIem9MdkVLRTJSRXoiLCJtYWMiOiI1ZjA2MGQ4OTk2YWI3Yzk2NzVmOGM5NmE5N2NmMjQxYzBlNzQwMjM0M2MyM2Q4YmJiMTUwNTg1ZjQzNWQyYTcwIn0%3D")
//                    .header("x-requested-with","XMLHttpRequest")
//                    .get();
//        SalePartner salePartner = new SalePartner();
//        salePartner.setSaleKey("Apxo85fHzxZGGehuyRD6bBI2N4yDODG754AmLFir");
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2tlamlubGlhbm1lbmcuY29tL2FwaV92MS9zeXN0ZW0vYXV0aC9sb2dpbiIsImlhdCI6MTcyNjcxNjYyMSwiZXhwIjoxNzI5MzA4NjIxLCJuYmYiOjE3MjY3MTY2MjEsImp0aSI6Ijh4eURpRXQ1Nk5tWGp0ejEiLCJzdWIiOjE0NywicHJ2IjoiNjdkMzEwNjAzOTdkZWJkNDIyMzYzMWMxMTc1NGNlMTRjNjYzNDJjMSIsInVzZXIiOnsidHlwZSI6InVzZXIiLCJzYWx0IjoiOTg2YzBiY2U4MjQ5NGYyODM2NzM3ZDdlZTEzMjc4NDAifX0.kqQwbHUDDdL4_rbMvUL5yPFi--yDpMSbQDlJRE4_3Fs";
        String body = HttpRequest.get(push)
                .header("Cookie", getCookie(salePartner) + "remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d=" + token)
                .header("x-requested-with", "XMLHttpRequest")
                .execute()
                .body();
        Document parse = Jsoup.parse(body);
        Elements metaTags = parse.select("meta");
        String content = metaTags.last().attr("content");
        log.info("content={}", content);
        return content;
    }

    private static String getCookie(SalePartner salePartner) {

//        String s = new Date().getTime() / 1000 + "";

        String cookie = "account=" + salePartner.getSaleKey() + "; _ga=GA1.1.2133416559.1726621808; acw_tc=ac11000117266272807932614e00e00608a859cf72b9d0f1ed3cb79246450c; _ga_TJJQCLLECR=GS1.1.1726627284.2.0.1726627284.0.0.0";
        return cookie;
    }

    /**
     * 发送验证码
     *
     * @return
     */
    private static void send(String phone) {
        String send = "https://kejinlianmeng.com/api_v1/system/captcha/send";

        TreeMap params = new TreeMap();
        params.put("passport", phone);
        params.put("type", "exist");
        String s = new Date().getTime() / 1000 + "";
        params.put("timestamp", s);
        String nonce = nonce();
        params.put("nonce", nonce);

        String sign = sign(params);
        params.put("sign", sign);

        String cookie = getCookie(null);

        JSONObject jsonObject = new JSONObject(params);
        String s3 = jsonObject.toString();
        System.out.println(s3);
        String body = HttpRequest.post(send)
                .header("x-app-source", "pc")
                .header("x-os", "pc")
                .header("x-type", "user")
                .header("x-ver", "2.39.0")
                .header("cookie", cookie)
                .body(s3)
                .execute()
                .body();
        log.info("验证码发送结果={}", body);
    }

    /**
     * 获取nonce
     *
     * @return
     */
    private static String nonce() {

        //md5加密（1234567890-随机6位数+时间戳+api）
        String s11 = new Date().getTime() / 1000 + "";
        String s1 = "1234567890" + r() + s11 + "0" + "/api_v1/system/captcha/send";
        String nonce = DigestUtils.md5Hex(s1);
        return nonce;
    }

    /**
     * 获取sign
     *
     * @param params
     * @return
     */
    private static String sign(TreeMap params) {
        //"captcha=1111111,device_id=,device_type=web,guard=web,nonce=4bdb0fdf5e07ce2e1a8f39b3b318fb00,passport=18537003990,password=,timestamp=1726220281"
        //按照参数排序后  + md5加密 = str1
        //
        //str1+"pc"+"2.39.0"   = l
        //
        //f + l[1]+l[3]+l[7]+l[15]+h+l[31]
        //f = l的数字的第一个
        //h = l的字母的最后一个
        String cover = MapUntils.getCover(params).replace("&", ",");
        String substring = cover.substring(0, cover.length() - 1);
        System.out.println(substring);
        String first = DigestUtils.md5Hex(substring);
        String scend = DigestUtils.md5Hex(first + "");
        String s2 = scend + "pc" + "2.39.0";
        String l = DigestUtils.md5Hex(s2);
        Pattern p1 = Pattern.compile("\\d+");
        Matcher m1 = p1.matcher(l);
        StringBuffer num = new StringBuffer();
        while (m1.find()) {
            num.append(m1.group());
        }
        String f = num.substring(0, 1);
        // 正则表达式匹配任何字母字符
        String pattern = "[a-zA-Z]+";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(l);
        StringBuffer hstr = new StringBuffer();
        while (m.find()) {
            hstr.append(m.group());
        }
        String sign = f + l.substring(1, 2) + l.substring(3, 4) + l.substring(7, 8) + l.substring(15, 16) + hstr.substring(hstr.length() - 1, hstr.length()) + l.substring(l.length() - 1, l.length());
        return sign;
    }

    private static String r() {
        Random random = new Random();
        int min = 1000000;
        int max = 9999999;

        Integer randomNumber = random.nextInt(max - min + 1) + min;
        System.out.println("随机六位: " + randomNumber);
        return randomNumber.toString();
    }

    String upLoadImg(String img, SalePartner salePartner) {
        byte[] bytes = AliUtils.downloadPicture(img);
        String name = img.substring(img.lastIndexOf("."));
        MultipartFile multipartFile = MultipartFileUtil.getMultipartFile(name, bytes);

        String endpoint = "oss-cn-shenzhen.aliyuncs.com";
        //先从redis取密钥
        String data = "";

        String body = HttpRequest.get("https://api.taohaohaoapp.com/app/sts").execute().body();
        data = JSONObject.parseObject(body).getString("data");

        String accessKeyId = JSONObject.parseObject(data).getString("AccessKeyId");
        String accessKeySecret = JSONObject.parseObject(data).getString("AccessKeySecret");
        String securityToken = JSONObject.parseObject(data).getString("SecurityToken");

        String string = null;
        try {
            string = AliUtils.uploadFile(multipartFile, endpoint, accessKeyId, accessKeySecret, "shenzhenbucket01", securityToken);
            return string;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static File convert(byte[] byteArray) throws IOException {
        File file = File.createTempFile("kankantemp", ".jpg");
//        imgUrl = file.getPath();
        Path path = Paths.get(file.getAbsolutePath());
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(byteArray);
        }catch (Exception e){

        }
        return file;
    }

}
